// SlagCar/StatisticsDetail/StatisticsDetail.js
let listBehavior = require('../../behavior/list'),
  today = wx.$util.formatDate(new Date(),'yyyy-MM-dd');
Page({
  behaviors: [ listBehavior, ],

  /**
   * 页面的初始数据
   */
  data: {
    list: [],

    requestApi: '',
    pageTitle: '',
    count: null,

    //统计工地参数
    delivery: {
      pageTitle: '泥头统计',
      fields: {
        titleFields: [
          {field: 'delivery_name'},
          {field: 'date',type: 'date'},
        ],
        contentFields:[
          {field: 'out_times',title: '趟数'},
          {field: 'amount',title: '金额'},
        ],
        childField: 'vehis',
        children:{
          contentFields: [
            {field: 'vehi_no',title: '车牌'},
            {field: 'out_times',title: '趟数'},
            {field: 'construction_amount',title: '金额'},
          ],
          bgColor: '#ebf2ff',
        }
      },
      requestApi: 'ZTAuth/EveryDayDeliveryStat'
    },
    //统计消纳场参数
    destination: {
      pageTitle: '泥尾统计',
      fields: {
        titleFields: [
          {field: 'destination_name'},
          {field: 'date',type: 'date'},
        ],
        contentFields:[
          {field: 'out_times',title: '趟数'},
          {field: 'amount',title: '金额'},
        ],
        childField: 'vehis',
        children:{
          contentFields: [
            {field: 'vehi_no',title: '车牌'},
            {field: 'out_times',title: '趟数'},
            {field: 'destination_amount',title: '金额'},
          ],
          bgColor: '#ebf2ff',
        }
      },
      requestApi: 'ZTAuth/EveryDayDestinationStat'

    },
    //统计车队
    fleet: {
      pageTitle: '按车队统计',
      fields: {
        titleFields: [
          {field: 'fleet_name'},
          {field: 'date',type: 'date'},
        ],
        contentFields:[
          {field: 'truck_count',title: '车辆数'},
          {field: 'out_times',title: '趟数'},
          {field: 'amount',title: '金额'},
        ],
        childField: 'fleet_division',
        children: {
          titleFields: [
            {field: 'fleet_division_name'},
          ],
          contentFields: [
            {field: 'truck_count',title: '车辆数'},
            {field: 'out_times',title: '趟数'},
            {field: 'amount',title: '金额'},
          ],
          childField: 'deliveries',
          bgColor: '#EBF1FF',

          children: {
            titleFields: [
              {field: 'delivery_name'},
            ],
            contentFields: [
              {field: 'truck_count',title: '车辆数'},
              {field: 'out_times',title: '趟数'},
              {field: 'amount',title: '金额'},
            ],
            childField: 'trucks',
            bgColor: '#d6e2ff',
            children:{
              contentFields: [
                {field: 'truck_number',title: '车牌'},
                {field: 'out_times',title: '趟数'},
                {field: 'amount',title: '金额'},
              ],
              bgColor: '#ebf2ff',
            }
          }
        }
      },
      requestApi: 'ZTAuth/EveryDayFleetStat'

    },
    //统计挖机
    excavator: {
      pageTitle: '按挖机统计',
      requestApi: 'ZTAuth/EveryDayExcavatorStat',
      fields: {
        titleFields: [
          {field: 'excavator_name'},
          {field: 'date',type: 'date'},
        ],
        contentFields:[
          {field: 'load_count',title: '装车数'},
        ],
        childField: 'deliveries',
        children: {
          titleFields: [
            {field: 'delivery_name'},
            {field: 'load_count'},
          ],
          bgColor: '#EBF1FF',
          /*contentFields: [
            {field: 'load_count',title: '装车数'},
          ],*/
          childField: 'destinations',
          children: {
            /*titleFields: [
              {field: 'vehi_no'},
              {field: 'destination_name'},
              {field: 'load_count',label: '装车数'},
            ],*/
            bgColor: '#d6e2ff',
            contentFields: [
              {field: 'vehi_no',title: '车牌'},
              {field: 'destination_name',title: '消纳场'},
              {field: 'load_count',title: '装车数'},
            ],
            /*childField: 'trucks',
            children:{
              contentFields: [
                {field: 'truck_number',title: '车牌'},
                {field: 'out_times',title: '趟数'},
                {field: 'amount',title: '金额'},
              ],
              bgColor: '#ebf2ff',
            }*/
          }

        }

      }
    },
    // 按材料统计
    goods: {
      pageTitle: '按材料统计',
      requestApi: 'ZTAuth/EveryDayGoodsAggregateSum',
      fields: {
        titleFields: [
          {field: 'goods_name'},
          {field: 'transport_times',label: '趟数'},
        ],
        /*contentFields:[
          {field: 'truck_count',title: '车辆数'},
          {field: 'out_times',title: '趟数'},
          {field: 'amount',title: '金额'},
        ],*/
        childField: 'excavators',
        children: {
          titleFields: [
            {field: 'excavator_name'},
            {field: 'transport_times',label: '趟数'},
          ],
          bgColor: '#EBF1FF',
          /*contentFields: [
            {field: 'truck_count',title: '车辆数'},
            {field: 'out_times',title: '趟数'},
            {field: 'amount',title: '金额'},
          ],*/
          childField: 'cars',

          children: {
            titleFields: [
              {field: 'car_no'},
              {field: 'transport_times',label: '趟数'},
            ],
            bgColor: '#d6e2ff',
            /*contentFields: [
              {field: 'truck_count',title: '车辆数'},
              {field: 'out_times',title: '趟数'},
              {field: 'amount',title: '金额'},
            ],
            childField: 'trucks',
            children:{
              contentFields: [
                {field: 'truck_number',title: '车牌'},
                {field: 'out_times',title: '趟数'},
                {field: 'amount',title: '金额'},
              ],
              bgColor: '#ebf2ff',
            }*/
          }
        }
      },

    },

    //快速搜索
    quickFlag: false,
    searchList: [
      {field_id: 'date',type: 'date',field_name: '日期',start: today,end: today },
    ],
    //提交搜索数据
    searchObj: {
      begin_date: today,
      end_date: today,
    },
  },

  //展开收起下级
  toggleShow(e){
    let {index} = e.currentTarget.dataset,
      {list } = this.data,
      obj = list[index];
    obj.isOpen = !obj.isOpen;
    this.setData({list})
  },
  //展开收起第三级
  toggleChildShow(e){
    let {index,par_index} = e.currentTarget.dataset,
      {childField,list } = this.data;
    let  obj = list[par_index][childField][index];
    obj.isOpen = !obj.isOpen;
    this.setData({list})

  },
  catchTap(){},

  //显示搜索
  showQuick(){
    this.setData({
      quickFlag: !this.data.quickFlag,
    })
  },
  //搜索变化
  searchChange({detail}){
    let {val,field_id} = detail,
      {searchObj} = this.data;
    if (field_id === 'date'){
      let {startDate,endDate} = val || {},
        obj = {
        begin_date: startDate || '',
        end_date: endDate || ''
      }
      searchObj = {...searchObj,...obj}
    } else {
      searchObj[field_id] = val
    }
    this.setData({searchObj});
  },
  //搜索数据
  searchData({detail}){
    let searchObj = {};
    //快速查询
    wx.$each(detail,(i,item)=>{
      let key = item.CompareWith;
      if (key === 'date'){
        if (item.Operator === '>='){ key = 'begin_date'; }
        if (item.Operator === '<=') { key = 'end_date'; }
      }
      searchObj[key] = item.CompareValue;
    });
    let {begin_date,end_date} = searchObj;
    if (!begin_date && !end_date) {
      wx.$toast('开始日期、结束日期不能为空');
      return
    }
    this.setData({searchObj});
    this.getFirstPage();

  },
  getDataList(){
    let {searchObj,page,limit,list,requestApi,user_type,pageTitle} = this.data,
      {begin_date,end_date,excavator_id} = searchObj;
   /* if (!begin_date && !end_date) {
      wx.$toast('开始日期、结束日期不能为空');
      return
    }*/
    if (!begin_date || !end_date) {
      begin_date = begin_date || end_date;
      end_date = end_date || begin_date
    }
    let url = requestApi + `/${begin_date}/${end_date}`,
      post = {only_my_chedui: user_type === 'carTeam'};
    if (pageTitle !== '按材料统计'){
      post['page.no'] = page
      post['page.size'] = limit
    }
    if (excavator_id)post.excavator_id = excavator_id;
    wx.$get(5,url,post).then(res=>{
      console.log(res);

      if (res.errcode != 0)return;
      let obj = {},
        total = res.page && res.page.totalsize,
        count = res.total;

      let rows = res.data && res.data.row || [];
      if(page !== 1) rows = [ ...list,...rows, ];
      if (pageTitle === '按材料统计') {
        total = rows.length;
      }
      obj = {total,list: rows,page,count};
      this.setData(obj);

    })
  },

  //获取挖机号
  getExcavators(){
    let post = {
        "table_id":"e_cheliangziliaobiao",
        "oby":"e_cheliangziliaobiao.row_id desc",
        "page":1,
        "limit":10,
        "SearchWhere":
          {
            "type":"and",
            "filters":[
              {"CompareWith":"e_cheliangziliaobiao.cheliangyongtu","Operator":"=","CompareValue":"挖机","or":0},
            ]
          }
      },
      where = [
        {"CompareWith":"e_cheliangziliaobiao.cheliangyongtu","Operator":"=","CompareValue":"挖机","or":0},
      ]
    this.getCustomData('e_cheliangziliaobiao',where).then(res =>{
      let {searchList} = this.data;
      searchList.push(
        {field_id: 'excavator_id',
          field_name: '挖机号',
          dfltVal: '',
          type: 'reference1',
          optionList: res,
          optionId: 'row_id',
          optionName: 'chelianghaoma'
        },)
      this.setData({searchList})
    })
  },
  //获取diy数据（
  getCustomData(table_id,where){
    let url = 'DynamicQuery/query_dynamic_v3',
      post = {limit: 0, page: 1, table_id,obj: `${table_id}.row_id`};
    where && (post.SearchWhere = {filters: where,type: 'and'});
    return new Promise(resolve => {
      wx.$post(3,url,post).then(res => {
        if (res.errcode != 0) return;
        resolve(res.data.row || [])
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let user_type = wx.getStorageSync('user_type');
    let {type} = options,
    // let type = 'delivery',
      data = this.data[type],
    {requestApi,pageTitle,fields} = data;
    this.setData({requestApi,pageTitle,fields,user_type})
    this.getDataList();
    if (type === 'excavator'){
      this.getExcavators();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})


